//
//  ERMapViewController.m
//  ExchangeRate
//
//  Created by 方义强 on 15/11/13.
//  Copyright © 2015年 方义强. All rights reserved.
//

#import "ERMapViewController.h"

#define kCLLocationAccuracyHundredMeter 100

@interface ERMapViewController () <MAMapViewDelegate, MAMapViewDelegate, AMapLocationManagerDelegate, AMapNearbySearchManagerDelegate, AMapSearchDelegate>

@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) AMapNearbySearchManager *nearbyManager;
@property (nonatomic, strong) AMapLocationManager *locationManager;
@property (nonatomic, strong) CLLocation *location;
@property (nonatomic, strong) AMapSearchAPI *search;
@property (nonatomic, strong) NSMutableArray *nearByArray;

@property (nonatomic, strong) UISearchBar *searchBar;

@property (nonatomic, assign) BOOL isSearch;

@end

@implementation ERMapViewController

- (NSMutableArray *)nearByArray
{
    if (!_nearByArray)
    {
        _nearByArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _nearByArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _leftButton.imageEdgeInsets = UIEdgeInsetsMake(10, 0, 10, 30);
    [_leftButton setImage:[UIImage imageNamed:@"iconfont-fanhui"] forState:(UIControlStateNormal)];
    [_leftButton addTarget:self action:@selector(didBackHomeViewAction) forControlEvents:(UIControlEventTouchUpInside)];
    self.view.backgroundColor = [UIColor whiteColor];
    [self addMapToView];
}

#pragma mark 显示地图
- (void)addMapToView
{
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 70, kSCREENWIDTH, kSCREENHEIGHT - 70)];
    _mapView.delegate = self; // 遵守协议
    _mapView.language = MAMapLanguageZhCN; // 语言
    [self.view addSubview:_mapView];

    // 调整高德地图的logo
    self.mapView.logoCenter = CGPointMake(10, self.view.bounds.size.height - 30);
    
    // 定位
    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode = MAUserTrackingModeFollowWithHeading;
    [_mapView setZoomLevel:16.1 animated:YES];
    _mapView.pausesLocationUpdatesAutomatically = NO;
//    _mapView.allowsBackgroundLocationUpdates = YES;//iOS9以上系统必须配置
    
    // 搜索附近
    _search = [[AMapSearchAPI alloc] init];
    _search.delegate = self;
}

#pragma mark 路线规划
- (void)addLineWayForNearBy:(AMapPOI *)p
{
    //构造AMapDrivingRouteSearchRequest对象，设置驾车路径规划请求参数
    AMapDrivingRouteSearchRequest *request1 = [[AMapDrivingRouteSearchRequest alloc] init];
    request1.origin = [AMapGeoPoint locationWithLatitude:p.location.latitude longitude:p.location.longitude];
    request1.destination = [AMapGeoPoint locationWithLatitude:p.location.latitude longitude:p.location.longitude];
    request1.strategy = 2;//距离优先
    request1.requireExtension = YES;
    
    //发起路径搜索
    [_search AMapDrivingRouteSearch: request1];
}

#pragma mark 路线回调函数
- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response
{
    if(response.route == nil)
    {
        return;
    }
    
    //通过AMapNavigationSearchResponse对象处理搜索结果
    NSString *route = [NSString stringWithFormat:@"Navi: %@", response.route];
    NSLog(@"%@", route);
}

#pragma mark 返回用户位置
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    if (updatingLocation)
    {
        NSLog(@"%f, %f", userLocation.coordinate.latitude, userLocation.coordinate.longitude);
        self.location = [[CLLocation alloc] initWithLatitude:userLocation.coordinate.latitude longitude:userLocation.coordinate.longitude];
        if (!_isSearch)
        {
            [self searchNearByMap];
            _isSearch = YES;
        }
    }
}
#pragma mark 以用户位置为中心显示用户位置
- (void)mapView:(MAMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
    MAAnnotationView *view = views[0];
    
    // 放到该方法中用以保证userlocation的annotationView已经添加到地图上了。
    if ([view.annotation isKindOfClass:[MAUserLocation class]])
    {
        MAUserLocationRepresentation *pre = [[MAUserLocationRepresentation alloc] init];
        pre.fillColor = [UIColor colorWithRed:0.9 green:0.1 blue:0.1 alpha:0.3];
        pre.strokeColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.9 alpha:1.0];
        pre.image = [UIImage imageNamed:@"location.png"];
        
        [self.mapView updateUserLocationRepresentation:pre];
        
        view.calloutOffset = CGPointMake(0, 0);
    }
}

#pragma mark 附近搜索功能
- (void) searchNearByMap
{
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude:_location.coordinate.latitude longitude:_location.coordinate.longitude];
    request.keywords = NSLocalizedString(@"银行", nil);
    // types属性表示限定搜索POI的类别，默认为：餐饮服务|商务住宅|生活服务
    // POI的类型共分为20种大类别，分别为：
    // 汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|
    // 医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|
    // 交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施
//    request.types = @"生活服务";
    request.sortrule = 0;
    request.requireExtension = YES;
    //发起附近周边搜索
    [_search AMapPOIAroundSearch:request];
}

#pragma mark 搜索周边回调函数
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    if(response.pois.count == 0)
    {
        return;
    }
    //通过 AMapPOISearchResponse 对象处理搜索结果
    NSString *strCount = [NSString stringWithFormat:@"count: %d",response.count];
    NSString *strSuggestion = [NSString stringWithFormat:@"Suggestion: %@", response.suggestion];
    NSString *strPoi = @"";
    for (AMapPOI *p in response.pois) {
        strPoi = [NSString stringWithFormat:@"%@\nPOI: %@", strPoi, p.name];
        [self.nearByArray addObject:p];
        [self addPointAnnotationOnMap:p];
    }
    NSString *result = [NSString stringWithFormat:@"%@ \n %@ \n %@", strCount, strSuggestion, strPoi];
    NSLog(@"Place: %@", result);
}

#pragma mark 添加大头针
- (void)addPointAnnotationOnMap:(AMapPOI *)p
{
    MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
    pointAnnotation.coordinate = CLLocationCoordinate2DMake(p.location.latitude, p.location.longitude);
    pointAnnotation.title = p.name;
    pointAnnotation.subtitle = p.address;
    [_mapView addAnnotation:pointAnnotation];
}

#pragma mark 返回home界面
- (void)didBackHomeViewAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
